﻿using AuthCenter.CSM.Common;
using AuthCenter.CSM.Dto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AuthCenter.CSM.plugins
{
    /// <summary>
    /// 用于当前登录的设备列表，和登出设备
    /// </summary>
    internal class DevicePlug : AuthCenterPluginBase
    {
        protected override string ListenUri { get; } = HttpCommon.SiteName + "/device";
        protected override async Task OnRequest(AuthCenterSession session)
        {
            if (session.IsPost(HttpCommon.SiteName+"/device"))
            {
                var output = new AuthCenterOutput();
                output.Success = true;

                if (session.IsAuthenticated)
                {
                    var data = await session.GetData<AuthCenterInput>();
                    switch (data.Method)
                    {
                        case "list-d":
                            var devices = session.db_device.GetOnlineDevice(session.UserID, session.AppID);
                            output.Params["devices"] = JsonConvert.SerializeObject(devices);
                            break;
                        case "shutdown-d":
                            var onlineId = data.GetID("oid");
                            session.db_device.ExpireOnline(onlineId);
                            session.db_log.Record("shutdown-device", $"{session.IP} 注销设备 {onlineId}", session.AppID, session.UserID);
                            break;
                        default:
                            output.Success = false;
                            break;
                    }
                }
                else
                {
                    output.Success = false;
                }

                await session.Send(200, output)
                        .AnswerAsync();//直接回应
            }

            //无法处理，调用下一个插件
            await session.InvokeNext();
        }
    }
}
